<template>
  <div class="wt-chat">
    <div class="wt-chat-container">
      <div class="message-list">
        <div
          v-for="(messageItem, index) in messageList"
          :key="`${messageItem.userId}-${index}`"
          class="message"
          :class="[messageItem.userId === userInfo.userId ? 'sender' : 'receiver']"
        >
          {{ messageItem.data }}
        </div>
      </div>

      <div class="chat-box">
        <textarea
          v-model="msg"
        />
        <Button type="primary"
          @click="handleSend"
        >发送</Button>
      </div>
    </div>

    <Modal
      title="登录"
      v-model="loginModalVisible"
      class-name="vertical-center-modal"
      :mask-closable="false"
      @on-ok="handleOk"
    >
      <Form :model="userInfo" :label-width="80">
        <FormItem label="用户名">
          <Input
            v-model="userInfo.userName"
            placeholder="输入用户名..."
          ></Input>
        </FormItem>
        <FormItem label="密码">
          <Input
            type="password"
            v-model="userInfo.password"
            placeholder="输入密码..."
          ></Input>
        </FormItem>
      </Form>

      <template #footer>
        <Button type="default" @click="loginModalVisible = false">取消</Button>
        <Button
          type="primary"
          @click="handleOk"
        >确认</Button>
      </template>
    </Modal>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import io from 'socket.io-client'
import useJwt from './useJwt';

const loginModalVisible = ref(true)
const socket = ref(null)
let timers = null
let count = 0
// 用户身份
const userInfo = ref({
  userId: '',
  userName: 'admin',
  password: '123456',
  token: ''
})

// 消息内容
const msg = ref('')
// 消息列表
const messageList = ref([
  // {
  //   userId: 'qid830k2',
  //   msgType: 'text',
  //   data: '我是发送者的消息'
  // }
])

// 开始计时
const startTimes = () => {
  timers = setInterval(() => {
    count++;
    console.log('等待时间', count , '秒')
  }, 1000)
}

// 重置时间
const resetTimes = () => {
  clearInterval(timers)
  count = 0
}

// 设置数据
const setAnswerData = (index, text) => {
  let count = 0;

  let t = setInterval(() => {
    messageList.value[index].data = text.substr(0, count)
    count++
    if (count >= text.length) {
      clearInterval(t)
    }
  }, 200)
}


// socket 初始化
const socketInit = () => {
  socket.value = io(
    'http://localhost:8000',
    {
      extraHeaders: {
        Authorization: `Bearer ${userInfo.value.token}`
      }
    }
  )

  // 监听文本消息
  socket.value.on('send_text_msg', msg => {
    if (Array.isArray(msg)) {
      messageList.value.push(...msg)
      return
    } 
    messageList.value.push({
      userId: msg.userId,
      msgType: 'text',
      data: msg.data
    })
  })

  socket.value.on('send_answer', msg => {
    messageList.value.push({
      userId: msg.userId,
      data: msg.data.substr(0, 1),
      msgType: 'text'
    })
    setAnswerData(messageList.value.length - 1, msg.data)
    resetTimes()
  })

  // 设置用户身份
  socket.value.on('user_info', userId => {
    if (!!userInfo.value.userId) {
      return
    }
    userInfo.value.userId = userId
  })
}

// 点击发送消息
const handleSend = () => {
  if (!msg.value) {
    return
  }

  try {
    // 发送文本消息
    // socket.value.emit('send_text_msg', {
    //   data: msg.value,
    //   userId: userInfo.value.userId
    // })

    socket.value.emit('send_question', {
      data: msg.value,
      userId: userInfo.value.userId
    })
    msg.value = ''
    startTimes()
  } catch {

  }
}

// 点击登录
const handleOk = () => {
  useJwt.login({
    name: userInfo.value.userName,
    password: userInfo.value.password
  }).then(res => {
    const { data } = res
    userInfo.value.token = data
    loginModalVisible.value = false

    // webSocket 初始化
    socketInit()
  }).catch(err => {
    console.log('登录失败', err)
  })
}
</script>

<style scoped>
.wt-chat {
  height: 80vh;
  border-radius: 5px;
  padding: 10vh 0;
}

.wt-chat-container {
  width: 80%;
  border: 1px solid #efefef;
  margin: 0 auto;
  height: 80vh;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
}

.message-list {
  padding: 10px;
  /* width: 150px; */
  flex: 1;

  display: flex;
  flex-direction: column;
  gap: 10px; /* 消息之间的间距 */
  padding: 20px;
  /* width: 300px; 示例宽度，可根据需要调整 */
  background-color: #f5f5f5; /* 背景颜色 */
  border-radius: 5px;
}


/* 消息通用样式 */
.message {
  max-width: 70%; /* 控制消息的最大宽度 */
  padding: 10px;
  border-radius: 10px;
  margin-bottom: 5px;
  font-size: 14px;
}

/* 发送者消息样式 */
.sender {
  align-self: flex-end; /* 消息靠右 */
  background-color: #DCF8C6; /* 示例颜色，表示发送者 */
}

/* 接收者消息样式 */
.receiver {
  align-self: flex-start; /* 消息靠左 */
  background-color: #E1E4E8; /* 示例颜色，表示接收者 */
}

.receiver-server {
  align-self: center; /* 消息靠左 */
  color: #fff;
  background-color: #E1E4E8; /* 示例颜色，表示接收者 */
}

/* 可选：为消息添加时间戳样式 */
.message::before {
  content: attr(data-time); /* 假设每个消息div有data-time属性存储时间戳 */
  display: block;
  color: #999;
  font-size: 12px;
  margin-bottom: 2px;
}

.chat-box {
  height: 200px;
  border-top: 1px solid #efefef;
  padding: 10px;
  position: relative;
}

.chat-box textarea {
  width: 100%;
  height: 100%;
  
  border: none;
  outline: none;
  /* 去掉右下角三角 */
  resize: none;
}

.chat-box button {
  position: absolute;
  bottom: 5px;
  right: 10px;
  padding: 5px 10px;
}

.vertical-center-modal{
  display: flex;
  align-items: center;
  justify-content: center;
}
.vertical-center-modal .ivu-modal{
    top: 0;
}
</style>